package face.jvm;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by zhangyanfei on 2019/6/25.
 *
 * @author zhangyanfei
 * @date 2019/06/25
 */
public class DemoSpinLock {
    /**
     * 公平锁  一上来先去判断同步队列是否为空 或者是否是同步队列的第一个节点 再去获取锁
     * 非公平锁 一上来就去尝试拿锁
     *
     * 重入锁  线程获取锁 执行相同锁的代码块时可以直接执行 synchronized
     *
     * 自旋锁
     * while循环 不用阻塞 线程上下文切换
     *
     * 独占锁  0 1
     *
     * 共享锁 +1 +1 +1
     *
     * 读写锁  CopyOnWriteArray  （volatile ReentrantLock）  AQS
     *
     * 理论 编码 小总结
     */
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t come in");
        while (!atomicReference.compareAndSet(null, thread)) {
            // doSomething()
        }
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t come out");
    }

    public static void main(String[] args) throws InterruptedException {
        DemoSpinLock demoSpinLock = new DemoSpinLock();

        new Thread(() -> {
            demoSpinLock.myLock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            demoSpinLock.unlock();
        }, "AA").start();
        Thread.sleep(1000);
        new Thread(() -> {
            demoSpinLock.myLock();
            demoSpinLock.unlock();
        }, "BB").start();
    }

}
